package com.bw.park2301.user

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.lib_base.mvvm.BaseActivity
import com.bw.lib_base.net.Const
import com.bw.park2301.R
import com.bw.park2301.databinding.ActivityLoginBinding
import dagger.hilt.android.AndroidEntryPoint
import retrofit2.http.Path

@AndroidEntryPoint
@Route(path = "/app/LoginActivity")
class LoginActivity : BaseActivity<ActivityLoginBinding, UserViewModel>() {

    override fun initView() {
        val loginTime = SPUtils.getInstance().getLong("loginTime", 0)
        val currentTime = System.currentTimeMillis()
        val day = (currentTime - loginTime) / 1000 / 60 / 60 / 24
        if (day < 7){
            start()
        }
        binding.btnLogin.setOnClickListener {
            val uname = binding.etUsername.text.toString()
            val pwd = binding.etPassword.text.toString()
            if (uname.isNullOrEmpty() || pwd.isNullOrEmpty()){
                ToastUtils.showLong("输入内容不能为空")
                return@setOnClickListener
            }
            if (!uname.matches(Regex("[A-z0-9_]{2,16}"))){
                ToastUtils.showLong("不是合法用户名")
                return@setOnClickListener
            }
            viewModel.login(pwd,uname)
        }

        binding.goReg.setOnClickListener {
            ARouter.getInstance().build("/app/RegisterActivity").navigation()
        }

    }

    override fun initData() {
        viewModel.loginData.observe(this){
            Log.i("zhy", it.toString())
            SPUtils.getInstance().apply {
                put(Const.TOKEN,it.token.toString())
                put(Const.UID, it.id)
                put(Const.USERNAME, it.username)
                put(Const.ROLE, "${it.roleid}")
                put("loginTime",System.currentTimeMillis())
            }
            start()
        }
    }

    fun start(){
        ARouter.getInstance().build("/app/MainActivity").navigation()
        finish()
    }
}